package utils;



import java.nio.charset.Charset;

/**
 * 字符串工具类
 * @author bug-fsh
 */
public class StringUtils {

    /**
     * 判断字符串为空
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        if (str == null || str.length() == 0) return true;
        return false;
    }

    public static void replace(StringBuffer stringBuffer, String sourceStr, String replaceStr) {
        int index = stringBuffer.indexOf(sourceStr);
        while (index != -1) {
            stringBuffer.replace(index, index + sourceStr.length(), replaceStr);
            index = stringBuffer.indexOf(sourceStr);
        }
    }

    public static String replace(String str, String sourceStr, String replaceStr) {
        StringBuffer stringBuffer = new StringBuffer(str);
        int index = stringBuffer.indexOf(sourceStr);
        while (index != -1) {
            stringBuffer.replace(index, index + sourceStr.length(), replaceStr);
            index = stringBuffer.indexOf(sourceStr);
        }
        return stringBuffer.toString();
    }

    public static String substringByte(String string, int startIndex, int endIndex, Charset charset) {
        String result = "";
        if (string == null || string.length() == 0) return result;
        byte [] bytes = string.getBytes(charset);
        int length = endIndex - startIndex + 1;
        byte [] substrBytes = new byte[endIndex - startIndex + 1];
        System.arraycopy(bytes, startIndex, substrBytes, 0, length);
        result = new String(substrBytes, charset);
        return result;
    }

    public static int length(String str) {
        if (str == null || str.length() == 0) return 0;
        return str.codePointCount(0, str.length());
    }

    public static String stringAt(String str, int index) {
        int [] codePoints = str.codePoints().toArray();
        return new String(codePoints, index, 1);
    }
    public static void main(String [] args) {
        String str = "abc  我是abc";
        System.out.println(substringByte(str, 5, 13, Charset.forName("utf-8")));
    }
}
